<?php

require_once IA_ROOT . '/addons/unpor_baby/common/defines.php';


/**
 * Created by PhpStorm.
 * User: benhailong
 * Date: 2018/10.09
 * Time: 下午10:57
 */
if (!(defined('IN_IA'))) {
    exit('Access Denied');
}

/**
 * UUID 生成工具
 */
function uuid(){
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}

/**
 * @param int $code
 * @param null $return
 */
function show_json($code = 0, $return = '')
{
    $ret = array('code' => $code, 'msg' => $return);
    exit(json_encode($ret));
}

function show_img_json($status = 0, $msg = '', $url = '')
{
    $ret = array('status' => $status, 'msg' => $msg, 'url' =>$url);
    exit(json_encode($ret));
}

/**
 * 分页返回json
 * @param int $code 状态码，一般返回0
 * @param string $msg 提示消息，可以为空
 * @param int $count 总条数
 * @param string $data 数据
 */
function page_show_json($code = 0, $msg = '', $count = 0, $data = ''){
    $ret = array('code' => $code, 'msg' => $msg, 'count' => $count, 'data' => $data);
    exit(json_encode($ret));
}

/**
 * POST 请求
 */
function curl_post_data($url, $body){ // 模拟提交数据函数

    $header = array(
        'Content-Type:application/x-www-form-urlencoded',
    );

    $ch = curl_init($url);
//    echo '$body = '.$body.'<br/><br/>';
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $result = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($result,true);
//    print_r('$result = '.$result);
    return $res;
}

/**
 * git 请求
 * @param $url
 * @param $data
 */
function http_get_data($url) {

    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    $res = json_decode($output,true);

    return $res;
}

/**
 * 删除空格
 */
function remove_null($str){
    $oldchar = array(" ","　","\t","\n","\r");
    $newchar = array("","","","","");
    return str_replace($oldchar,$newchar,$str);
}

//////////////////////////////////////////////////////////////////////////////////


function http_post_data($url, $data) {

    //将数组转成json格式
    $data = json_encode($data);

    //1.初始化curl句柄
    $ch = curl_init();

    //2.设置curl
    //设置访问url
    curl_setopt($ch, CURLOPT_URL, $url);

    //捕获内容，但不输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //模拟发送POST请求
    curl_setopt($ch, CURLOPT_POST, 1);

    //发送POST请求时传递的参数
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    //设置头信息
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data))
    );

    //3.执行curl_exec($ch)
    $return_content = curl_exec($ch);

    //如果获取失败返回错误信息
    if($return_content === FALSE){
        $return_content = curl_errno($ch);
    }

    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    //4.关闭curl
    curl_close($ch);

    return array($return_code, $return_content);
}

/////////////////////////////////////////////////////////////////////////////////

/**
 * 排序
 */
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

////////////////////////////////////////////////////////////////////////////////

function postData($url, $data = array(), $data1 = array()){
    $header = array(
        'Content-Type: multipart/form-data',
    );
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt ($ch, CURLOPT_BINARYTRANSFER,true);
    //curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
    curl_custom_postfields($ch, $data, $data1);
    $dxycontent = curl_exec($ch);
    curl_close($ch);
    return $dxycontent;
}

// PHP判断是不是以某个字符串开头
function startwith($str,$pattern) {
    if(strpos($str,$pattern) === 0)
        return true;
    else
        return false;
}


/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 *
 * @param resource $ch cURL resource
 * @param array $assoc "name => value"
 * @param array $files "name => path"
 * @return bool
 */
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {
    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}
